package com.mallsystem.userservice.controller;

import com.mallsystem.common.bean.Addr;
import com.mallsystem.common.bean.RespBean;
import com.mallsystem.common.exception.AllException;
import com.mallsystem.common.service.UserAddrService;
import com.mallsystem.common.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
@CrossOrigin
@RestController
@RequestMapping("/addr")
public class UserAddrController {
    @Autowired
    private UserAddrService userAddrService;
    //添加
    @PostMapping
    public RespBean insert(@RequestBody Addr addr,@RequestHeader("token") String token){
        //解析token
        Map<String, Object> map = JwtUtil.parseJwtToMap(token);
        //获取用户id - 根据id查询用户信息
        Integer userId = (Integer) map.get("id");
        addr.setUserId(userId);
        userAddrService.insert(addr);
        return RespBean.ok("添加成功");
    }
    //删除
    @DeleteMapping("/{id}")
    public RespBean delete(@PathVariable("id") Integer id,@RequestHeader("token") String token) throws AllException {
        //解析token
        Map<String, Object> map = JwtUtil.parseJwtToMap(token);
        //获取用户id - 根据id查询用户信息
        Integer userId = (Integer) map.get("id");
        userAddrService.delete(id,userId);
        return RespBean.ok("删除成功");
    }
    //修改
    @PutMapping
    public RespBean update(@RequestBody Addr addr,@RequestHeader("token") String token) throws AllException {
        //解析token
        Map<String, Object> map = JwtUtil.parseJwtToMap(token);
        //获取用户id - 根据id查询用户信息
        Integer userId = (Integer) map.get("id");
        userAddrService.update(addr,userId);
        return RespBean.ok("修改成功");
    }
    //查询当前用户的所有地址信息
    @GetMapping
    public RespBean selectByUser(@RequestHeader("token") String token){
        //解析token
        Map<String, Object> map = JwtUtil.parseJwtToMap(token);
        //获取用户id - 根据id查询用户信息
        Integer userId = (Integer) map.get("id");
        Addr condition = new Addr();
        condition.setUserId(userId);
        List<Addr> addrList = userAddrService.selectByCondition(condition);
        return RespBean.ok("查询成功",addrList);

    }
    //根据id查询
    @GetMapping("/{id}")
    public RespBean selectById(@PathVariable("id") Integer id){
        Addr addr = userAddrService.selectById(id);
        return RespBean.ok("查询成功",addr);
    }
}
